#!/bin/bash

. $TONE_ROOT/lib/testinfo.sh
. $TONE_ROOT/lib/common.sh
nginx_conf=/etc/nginx/nginx.conf
nr_open_default=$(cat /proc/sys/fs/nr_open)

clear_keentuneUI_env()
{
    rm -rf /usr/bin/chromedriver && yum remove google-chrome-stable.x86_64 -y
    if [ $? = 0 ]; then
      yum list google-chrome-stable.x86_64 && echo "Uninstall the success"
    fi
}

clear_keentune_env()
{
    rm -rf /usr/local/lib/python3.6/site-packages/keentune*
    rm -rf /usr/local/lib/python3.6/site-packages/brain
    rm -rf /usr/local/lib/python3.6/site-packages/target
    rm -rf /usr/local/lib/python3.6/site-packages/bench
    rm -f /usr/local/bin/keentune*
    ps -ef|grep -E 'keentuned|keentune-brain|keentune-target|keentune-bench'|grep -v grep|awk '{print $2}'| xargs -I {} kill -9 {}
}

clear_log_files()
{
    rm -rf /var/log/bench*
    rm -rf /var/log/brain*
    rm -rf /var/log/target*
    rm -rf /var/log/keentune*
    rm -rf /var/keentune/backup/param_set*
}

build_keentune()
{
    cd $TONE_BM_RUN_DIR

    cd keentuned
    go mod vendor
    ./keentuned_install.sh

    cd ../keentune-brain
    python3 setup.py install

    cd ../keentune-target
    python3 setup.py install

    cd ../keentune-bench
    python3 setup.py install

    cd $TONE_BM_RUN_DIR
}

setup()
{
    logger clear_keentune_env
    logger clear_log_files
    logger "build_keentune || exit 1"
    echo "this is run KeenTune UI test cases!"
}

run()
{
    cd $TONE_BM_RUN_DIR/
    log_suffix="$code_source-$test_branch-log-$(date +"%Y-%m-%d-%H-%M-%S")"
    keentuned > keentuned-$log_suffix 2>&1 &
    keentune-brain > keentune-brain-$log_suffix 2>&1 &
    keentune-bench > keentune-bench-$log_suffix 2>&1 &
    keentune-target > keentune-target-$log_suffix 2>&1 &
    sleep 5

    logger cd $TONE_BM_RUN_DIR/keentuned/test/KeenTune_UI
    echo -e "Start test:python3 main.py\nTests will ta severkeal minutes, pls wait"
    python3 main.py localhost

    if [ $? -ne 0 ]; then
        cd $TONE_BM_RUN_DIR/
        echo "ERROR:python3 main.py failed"
    fi

    cd $TONE_BM_RUN_DIR/
}

parse()
{
    awk -f $TONE_BM_SUITE_DIR/parse.awk
}

teardown()
{
    clear_keentuneUI_env
    [ -s "${nginx_conf}_bak" ] && \cp ${nginx_conf}_bak $nginx_conf
    systemctl stop nginx
    clear_log_files
    clear_keentune_env
    [ -n "$nr_open_default" ] && sysctl -w fs.nr_open=$nr_open_default
}